package com.example.ziliao.ui.special_growth

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.example.ziliao.databinding.FragmentSpecialGrowthBinding
import com.example.ziliao.utils.NumberGenerator
import kotlin.random.Random

class SpecialGrowthFragment : Fragment() {
    private var _binding: FragmentSpecialGrowthBinding? = null
    private val binding get() = _binding!!

    private lateinit var buttonStart: Button
    private lateinit var buttonShowAnswer: Button
    private lateinit var value1: TextView
    private lateinit var value2: TextView
    private lateinit var value3: TextView
    private lateinit var value4: TextView
    private lateinit var value5: TextView
    private lateinit var value6: TextView
    private lateinit var value7: TextView
    private lateinit var value8: TextView
    private lateinit var question1: TextView
    private lateinit var question2: TextView
    private lateinit var question3: TextView
    private lateinit var question4: TextView
    private lateinit var question5: TextView
    private lateinit var question6: TextView
    private lateinit var question7: TextView

    private var currentNumbers: List<Double> = emptyList()
    private var currentCount: Int = 0

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentSpecialGrowthBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        try {
            initViews()
            setupClickListeners()
        } catch (e: Exception) {
            Log.e("SpecialGrowthFragment", "Initialization error", e)
            Toast.makeText(requireContext(), "初始化失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }

    private fun initViews() {
        buttonStart = binding.buttonStart
        buttonShowAnswer = binding.buttonShowAnswer
        value1 = binding.value1
        value2 = binding.value2
        value3 = binding.value3
        value4 = binding.value4
        value5 = binding.value5
        value6 = binding.value6
        value7 = binding.value7
        value8 = binding.value8
        question1 = binding.question1
        question2 = binding.question2
        question3 = binding.question3
        question4 = binding.question4
        question5 = binding.question5
        question6 = binding.question6
        question7 = binding.question7
    }

    private fun setupClickListeners() {
        buttonStart.setOnClickListener {
            try {
                resetViews()
                generateNumbers()
            } catch (e: Exception) {
                Log.e("SpecialGrowthFragment", "Start button error", e)
                Toast.makeText(requireContext(), "生成数据失败: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }

        buttonShowAnswer.setOnClickListener {
            try {
                showAnswers()
            } catch (e: Exception) {
                Log.e("SpecialGrowthFragment", "Show answer error", e)
                Toast.makeText(requireContext(), "显示答案失败: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun generateNumbers() {
        // 随机选择生成6或8个数
        currentCount = if (Random.nextBoolean()) 6 else 8
        
        // 生成第一个随机数
        val number1 = NumberGenerator.generateRandomNumber()
        val numbers = mutableListOf(number1)
        
        // 生成后续随机数
        for (i in 1 until currentCount) {
            val prevNumber = numbers.last()
            val ratio = Random.nextDouble(0.8, 1.6)
            numbers.add(prevNumber * ratio)
        }

        currentNumbers = numbers

        // 显示数值
        value1.text = formatNumber(numbers[0])
        value2.text = formatNumber(numbers[1])
        value3.text = formatNumber(numbers[2])
        value4.text = formatNumber(numbers[3])
        value5.text = formatNumber(numbers[4])
        value6.text = formatNumber(numbers[5])
        
        if (currentCount == 8) {
            value7.text = formatNumber(numbers[6])
            value8.text = formatNumber(numbers[7])
            value7.visibility = View.VISIBLE
            value8.visibility = View.VISIBLE
        } else {
            value7.visibility = View.GONE
            value8.visibility = View.GONE
        }

        // 显示所有数值
        value1.visibility = View.VISIBLE
        value2.visibility = View.VISIBLE
        value3.visibility = View.VISIBLE
        value4.visibility = View.VISIBLE
        value5.visibility = View.VISIBLE
        value6.visibility = View.VISIBLE

        // 显示问题和"显示答案"按钮
        question1.visibility = View.VISIBLE
        question2.visibility = View.VISIBLE
        question3.visibility = View.VISIBLE
        question4.visibility = View.VISIBLE
        question5.visibility = View.VISIBLE
        question6.visibility = View.VISIBLE
        question7.visibility = View.VISIBLE
        buttonShowAnswer.visibility = View.VISIBLE
    }

    private fun showAnswers() {
        // 计算各种增幅的数量
        val counts = calculateCounts()

        // 更新问题文本
        question1.text = "降幅超过10%的有${counts[0]}个"
        question2.text = "增幅在2%-5%的有${counts[1]}个"
        question3.text = "增幅在5%-10%的有${counts[2]}个"
        question4.text = "增幅在10%-15%的有${counts[3]}个"
        question5.text = "增幅在15%-20%的有${counts[4]}个"
        question6.text = "增幅在20%以上的有${counts[5]}个"
    }

    private fun calculateCounts(): List<Int> {
        val counts = mutableListOf(0, 0, 0, 0, 0, 0)
        
        for (i in 1 until currentCount) {
            val ratio = currentNumbers[i] / currentNumbers[i - 1]
            val growth = (ratio - 1) * 100

            when {
                growth < -10 -> counts[0]++ // 降幅超过10%
                growth in 2.0..5.0 -> counts[1]++ // 增幅在2%-5%
                growth in 5.0..10.0 -> counts[2]++ // 增幅在5%-10%
                growth in 10.0..15.0 -> counts[3]++ // 增幅在10%-15%
                growth in 15.0..20.0 -> counts[4]++ // 增幅在15%-20%
                growth > 20.0 -> counts[5]++ // 增幅在20%以上
            }
        }
        
        return counts
    }

    private fun formatNumber(number: Double): String {
        return when {
            number < 1000 -> {
                when (Random.nextInt(2)) {
                    0 -> String.format("%.1f", number)
                    else -> String.format("%.2f", number)
                }
            }
            else -> String.format("%.0f", number)
        }
    }

    private fun resetViews() {
        // 隐藏所有数值
        value1.visibility = View.GONE
        value2.visibility = View.GONE
        value3.visibility = View.GONE
        value4.visibility = View.GONE
        value5.visibility = View.GONE
        value6.visibility = View.GONE
        value7.visibility = View.GONE
        value8.visibility = View.GONE
        
        // 重置并隐藏所有问题
        question1.text = "降幅超过10%的有____个"
        question2.text = "增幅在2%-5%的有____个"
        question3.text = "增幅在5%-10%的有____个"
        question4.text = "增幅在10%-15%的有____个"
        question5.text = "增幅在15%-20%的有____个"
        question6.text = "增幅在20%以上的有____个"
        
        question1.visibility = View.GONE
        question2.visibility = View.GONE
        question3.visibility = View.GONE
        question4.visibility = View.GONE
        question5.visibility = View.GONE
        question6.visibility = View.GONE
        buttonShowAnswer.visibility = View.GONE
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}